package com.yj.auto.core.jfinal.interceptor;

import java.util.regex.Pattern;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.StrKit;
import com.yj.auto.core.jfinal.base.BaseCache;

/**
 * 刷新缓存
 */
public class CacheRefreshInterceptor implements Interceptor {

	private Pattern pattern;

	public CacheRefreshInterceptor(String regex) {
		this(regex, true);
	}

	public CacheRefreshInterceptor(String regex, boolean caseSensitive) {
		if (StrKit.isBlank(regex))
			throw new IllegalArgumentException("regex can not be blank.");
		pattern = caseSensitive ? Pattern.compile(regex) : Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
	}

	public void intercept(final Invocation inv) {
		inv.invoke();

		if (!pattern.matcher(inv.getMethodName()).matches())
			return;

		Object bool = inv.getReturnValue();
		// 拦截方法必须返回布尔值
		if (bool instanceof Boolean && (Boolean) bool) {
			Object obj = inv.getTarget();
			if (obj instanceof BaseCache) {//清空缓存，等等重新加载
				// System.err.println(inv.getTarget().getClass()+"."+inv.getMethodName());
				((BaseCache) obj).clearCache();
			}
		}
	}

}
